package JUC;

import java.util.concurrent.atomic.AtomicInteger;

class MyData{
    volatile int number = 0;

    public void addTo70() {
        this.number = 70;
    }

    public void addPlusPlus(){
        this.number++;
    }

    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus2(){
        atomicInteger.getAndIncrement();
    }
}

public class VolatileDemo {


}

class notAtomicVolatileDemo{
    public static void main(String[] args) {
        MyData data = new MyData();
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    data.addPlusPlus();
                    data.addPlusPlus2();
                } }, String.valueOf(i)).start();
        }

        while (Thread.activeCount() > 2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() +
                ": final number is : " + data.number);
        System.out.println(Thread.currentThread().getName() +
                ": final atomic number is : " + data.atomicInteger);
    }
}

class seeOkVolatileDemo {
    public static void main(String[] args) throws InterruptedException {
        MyData data = new MyData();
        new Thread(()->{data.addTo70();
            System.out.println(Thread.currentThread().getName() +
                    ": " + data.number);}, "AAA").start();

        Thread.sleep(2000);
        while (data.number == 0){

        }
        System.out.println(Thread.currentThread().getName() +
                ": number is updated,the value is :" + data.number);
    }
}
